<?php if(!defined('FRAME')) exit('No direct script access allowed');
/**
 * 自动加载类
 * @author wisoch@hotmail.com
 *
 */
class Autoloader {

	private $application;

	private static $loader;

	public static function init($application) {
		if(is_null(self::$loader)) self::$loader = new self($application);
		return self::$loader;
	}
	
	public function __construct($application) {
		$this->application = $application;
		
		set_include_path(get_include_path() . PATH_SEPARATOR . $this->application . '/');
		
		spl_autoload_register(array($this, '__autoloader'));
		spl_autoload_register(array($this, 'model'));
		spl_autoload_register(array($this, 'data'));
	}

	public function __autoloader($class) {
		$str = str_replace('_', DS, $class);
		if(file_exists(FRAME . DS . $str.'.php')) {
			spl_autoload_extensions('.php');
			spl_autoload($class);
		}
	}

	public function model($class) {
		$replaced = preg_replace('/_model$/ui','',$class);
		
        if($replaced != $class) {
			$model = $this->application . '/model/' . $replaced . '.model.php';
			if(file_exists($model)) {
				include $model;
			}
		}
    }

    public function data($class) {
		$replaced = preg_replace('/_data$/ui','',$class);
		
        if($replaced != $class) {
			$data = $this->application . '/data/' . $replaced . '.data.php';
			if(file_exists($data)) {
				include $data;
			}
		}
    }
}